package util

import (
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"math/rand"
	"net"
	"net/http"
	"time"
)

// RandomString 生成随机数
func RandomString(n int) string {
	var letters = []byte("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM")
	result := make([]byte, n)
	rand.Seed(time.Now().Unix())
	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

// GetLocalIP 获取客户端IP
func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

// GetRemoteClientIp 获取远程客户端IP
func GetRemoteClientIp(r *http.Request) string {
	remoteIp := r.RemoteAddr

	if ip := r.Header.Get("X-Real-IP"); ip != "" {
		remoteIp = ip
	} else if ip = r.Header.Get("X-Forwarded-For"); ip != "" {
		remoteIp = ip
	} else {
		remoteIp, _, _ = net.SplitHostPort(remoteIp)
	}

	//本地ip
	if remoteIp == "::1" {
		remoteIp = "127.0.0.1"
	}

	return remoteIp
}

// ShowDistance 距离显示
func ShowDistance(n float64) string {
	if n < 1000 {
		return fmt.Sprintf("%.2f", n) + "m"
	}
	return fmt.Sprintf("%.2f", n/1000) + "km"
}

func DateFormat(sec int64) string {
	var timestamp int64
	if sec <= 0 {
		timestamp = time.Now().Unix()
	} else {
		timestamp = sec
	}
	timeobj := time.Unix(timestamp, 0)
	date := timeobj.Format("2006-01-02 15:04:05")
	return date
}
func DateFormatNotTime(sec int64) string {
	var timestamp int64
	if sec <= 0 {
		timestamp = time.Now().Unix()
	} else {
		timestamp = sec
	}
	timeobj := time.Unix(timestamp, 0)
	date := timeobj.Format("2006-01-02")
	return date
}

func OrderNumber() string {
	timeobj := time.Unix(time.Now().Unix(), 0)
	date := timeobj.Format("20060102150405")

	return date + RandomString(6)
}

// Substr //start：正数 - 在字符串的指定位置开始,超出字符串长度强制把start变为字符串长度
// //       负数 - 在从字符串结尾的指定位置开始
// //       0 - 在字符串中的第一个字符处开始
// //length:正数 - 从 start 参数所在的位置返回
// //       负数 - 从字符串末端返回
func Substr(str string, start int, length int) string {

	runeStr := []rune(str)
	lenStr := len(runeStr)

	if start < 0 {
		start = lenStr + start
	}
	if start > lenStr {
		start = lenStr
	}
	end := start + length
	if end > lenStr {
		end = lenStr
	}
	if length <= 0 {
		end = lenStr + length
	}
	if start > end {
		start, end = end, start
	}
	return string(runeStr[start:end])
}

// MD5 封装成类似php md5用法
func MD5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

// SHA1 封装成类似php sha1用法
func SHA1(s string) string {

	o := sha1.New()

	o.Write([]byte(s))

	return hex.EncodeToString(o.Sum(nil))

}
